import styles from "./index.module.scss";
import MainEdit from './components/MainEdit';
import Results from './components/Results';
import History from './components/History';
import { Button,Image,Toast,Modal,Upload } from '@douyinfe/semi-ui';
import download from "@/assets/images/imageEdit/download.svg";
import add_gray from "@/assets/images/add_gray.svg";
import { Timeline, TimelineEngine } from '@xzdarcy/react-timeline-editor';
import { useState, useRef, useMemo, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { replaceContent,erasureContent,syntheticVideo } from '@/api/filmRoto';
import { selectCurrentVideo, clearLayerVideo } from '@/store/slices/imageEditSlice';
import sharedWebSocket from '@/services/sharedWebSocket';
import { useImageUpload } from '@/hooks/useImageUpload';


export default function ImageEditPage() {
  const dispatch = useDispatch();
  const currentVideo = useSelector(selectCurrentVideo);

  const [showMainEdit, setShowMainEdit] = useState(false);
  const [showResults, setShowResults] = useState(true);
  const [selectedTool, setSelectedTool] = useState(null); // 默认选择点选工具
  const [toolSize, setToolSize] = useState(20); // 工具大小
  const [selectedRatio, setSelectedRatio] = useState('16:9'); // 画幅比例
  const [step, setStep] = useState(0); // 步骤状态
  const [videoLoadError, setVideoLoadError] = useState(false); // 视频加载错误状态

  // 当step变为1时（上传完成），自动显示MainEdit
  useEffect(() => {
    if (step === 1) {
      setShowMainEdit(true);
    }
  }, [step]);

  const engine = new TimelineEngine();
  const timelineRef = useRef(engine);
  
  // 时间轴配置
  const [timelineConfig, setTimelineConfig] = useState({
    scale: 5,
    startLeft: 20,
    scaleWidth: 150,
    scaleSplitCount: 5,
    level: 1
  });
  
  const timelineConfigRef = useRef(timelineConfig);
  timelineConfigRef.current = timelineConfig;
    
  const resultsContainerRef = useRef(null);
  


  // 片段管理相关状态
  const [segments, setSegments] = useState([]); // 片段列表
  const [selectedSegmentId, setSelectedSegmentId] = useState(null); // 当前选中的片段ID
  const [timelineData, setTimelineData] = useState([{ id: 1, actions: [] }]); // 时间轴数据
  
  // 视频播放控制状态
  const [isVideoPlaying, setIsVideoPlaying] = useState(false);
  const [currentVideoTime, setCurrentVideoTime] = useState(0);
  const [videoDuration, setVideoDuration] = useState(0);

  // 格式化时间为字符串
  const formatTimeToString = (seconds) => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    const milliseconds = Math.round((seconds % 1) * 1000);
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')},${milliseconds.toString().padStart(3, '0')}`;
  };
  
  // 监听播放时间变化
  useEffect(() => {
    const handleSetTimeByTick = ({ time }) => {  
      // 时间轴容器宽度
      const timelineContainer = document.querySelector(`.${styles.timelineWrap}`);
      if (!timelineContainer) return;
      const autoScrollFrom = timelineContainer.clientWidth - 10;
      // 计算滚动位置
      const { scaleWidth, scale, startLeft } = timelineConfigRef.current;
      const left = time * (scaleWidth / scale) + startLeft - autoScrollFrom;
      timelineRef.current.setScrollLeft(left);
    };

    timelineRef.current.listener.on('setTimeByTick', handleSetTimeByTick);

    return () => {
      if (timelineRef.current) {
        timelineRef.current.listener.off('setTimeByTick', handleSetTimeByTick);
      }
    };
  }, []);
  
  // 鼠标滚轮缩放
  useEffect(() => {
    const timelineContainer = document.querySelector(`.${styles.timelineWrap}`);
    if (!timelineContainer) return;

    const handleWheel = (e) => {
      e.preventDefault();
      const delta = e.deltaY > 0 ? 1 : -1; // 往上缩小，往下放大
      let level = timelineConfig.level + delta;
      
      if (level < 1) {
        level = 1;
        return;
      }
      if (level > 4) {
        level = 4;
        return;
      }
      
      // 基于秒的缩放步长，不再依赖帧率
      let scaleStep = 5;

      let newScale = Math.max(5, timelineConfig.scale + delta * scaleStep);
      
      // 当缩小时（delta < 0），检查是否会导致刻度无法充满容器
      if (delta > 0) {
        const containerWidth = timelineContainer?.clientWidth;
        // 计算容器能显示的最大刻度数量
        const maxVisibleScales = Math.ceil(containerWidth / timelineConfig.scaleWidth);
        // 计算缩放后的视频总刻度数量
        const totalScalesAfterZoom = Math.floor(document.querySelector('video').duration / newScale);

        // 如果容器能显示的刻度数量大于等于视频总刻度数，不允许继续缩小
        if (maxVisibleScales > totalScalesAfterZoom+1) {
          return; // 阻止缩小
        }
      }
      
      // 更新缩放比例
      setTimelineConfig(prev => ({ ...prev, scale: newScale, level }));
      if (newScale !== timelineConfig.scale) {
        // 缩放后保持当前播放位置不变
        setTimeout(() => {
          const currentTime = timelineRef.current.getTime();
          const containerWidth = timelineContainer.clientWidth;
          const autoScrollFrom = containerWidth - 10;
          // 重新算位置
          const left = currentTime * (timelineConfig.scaleWidth / newScale) + timelineConfig.startLeft - autoScrollFrom;
          if (timelineRef.current.setScrollLeft) {
            timelineRef.current.setScrollLeft(left);
          }
        }, 100);
      }
    };

    timelineContainer.addEventListener('wheel', handleWheel, { passive: false });

    return () => {
      timelineContainer.removeEventListener('wheel', handleWheel);
    };
  }, [timelineConfig]);

  // 视频播放控制函数
  const formatTime = (seconds) => {
    if (!seconds || isNaN(seconds)) return '00:00';
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const handlePlayPause = () => {
    const targetVideo = getTargetVideo();
    
    if (targetVideo) {
      if (isVideoPlaying) {
        targetVideo.pause();
        // 暂停时间轴
        if (timelineRef.current && timelineRef.current.pause) {
          timelineRef.current.pause();
        }
      } else {
        targetVideo.play().catch(console.error);
        // 播放时间轴
        if (timelineRef.current && timelineRef.current.play) {
          timelineRef.current.play();
        }
      }
      setIsVideoPlaying(!isVideoPlaying);
    }
  };

  const getTargetVideo = () => {
    if (selectedPreviewMode === 'result') {
      // 预览模式：查找预览视频
      return document.querySelector('#preview-video');
    } else {
      // 原视频模式：查找在#current-video容器内的video元素
      return document.querySelector('#current-video video');
    }
  };

  const handleRewind = () => {
    const video = getTargetVideo();
    if (video) {
      const newTime = Math.max(0, video.currentTime - 10);
      video.currentTime = newTime;
      
      // 同步更新时间轴指针位置
      if (timelineRef.current && timelineRef.current.setTime) {
        timelineRef.current.setTime(newTime);
      }
    }
  };

  const handleFastForward = () => {
    const video = getTargetVideo();
    if (video) {
      const newTime = Math.min(video.duration, video.currentTime + 10);
      video.currentTime = newTime;
      
      // 同步更新时间轴指针位置
      if (timelineRef.current && timelineRef.current.setTime) {
        timelineRef.current.setTime(newTime);
      }
    }
  };

  const handleProgressClick = (e) => {
    const video = getTargetVideo();
    if (video && videoDuration) {
      const rect = e.currentTarget.getBoundingClientRect();
      const clickX = e.clientX - rect.left;
      const percentage = clickX / rect.width;
      const newTime = percentage * videoDuration;
      video.currentTime = newTime;
      setCurrentVideoTime(newTime);
      
      // 同步更新时间轴指针位置
      if (timelineRef.current && timelineRef.current.setTime) {
        timelineRef.current.setTime(newTime);
      }
    }
  };

  // 监听视频播放状态
  useEffect(() => {
    if (!currentVideo) return;
    
    const video = document.querySelector('video');
    if (!video) return;

    const handleTimeUpdate = () => {
      setCurrentVideoTime(video.currentTime);
      // 通知时间轴更新 - 直接使用秒作为时间单位
      if (timelineRef.current && timelineRef.current.listener && typeof timelineRef.current.listener.emit === 'function') {
        timelineRef.current.listener.emit('setTimeByTick', { time: video.currentTime });
      }
    };

    const handleLoadedMetadata = () => {
      setVideoDuration(video.duration);
      console.log('视频时长已获取:', video.duration);
    };

    const handlePlay = () => {
      setIsVideoPlaying(true);
      // 视频播放时，启动时间轴
      if (timelineRef.current && timelineRef.current.play) {
        timelineRef.current.play();
      }
    };

    const handlePause = () => {
      setIsVideoPlaying(false);
      // 视频暂停时，暂停时间轴
      if (timelineRef.current && timelineRef.current.pause) {
        timelineRef.current.pause();
      }
    };

    video.addEventListener('timeupdate', handleTimeUpdate);
    video.addEventListener('loadedmetadata', handleLoadedMetadata);
    video.addEventListener('play', handlePlay);
    video.addEventListener('pause', handlePause);

    // 初始化 - 如果视频已经加载完成
    if (video.duration && !isNaN(video.duration)) {
      setVideoDuration(video.duration);
      console.log('初始化视频时长:', video.duration);
    }
    setIsVideoPlaying(!video.paused);
    setCurrentVideoTime(video.currentTime);

    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate);
      video.removeEventListener('loadedmetadata', handleLoadedMetadata);
      video.removeEventListener('play', handlePlay);
      video.removeEventListener('pause', handlePause);
    };
  }, [currentVideo]);

  // 组件卸载时清理图片数据
  useEffect(() => {
    return () => {
      dispatch(clearLayerVideo());
    };
  }, [dispatch]);

  // WebSocket消息监听
  useEffect(() => {
    const handleWebSocketMessage = (data) => {
      // 处理分割成功消息
      if (data.func === 'video_tracking_success' && data.operId) {
        setSegments(prevSegments => {
          return prevSegments.map(segment => {
            if (segment.id === data.operId) {
              return {
                ...segment,
                state: 'TRACK_SUCCESS',
                videoUrl: data.data.videoUrl,
                maskUrls: data.data.maskUrls,
              };
            }
            return segment;
          });
        });
        setSelectedPreviewMode('result');
      }
      // 处理分割失败消息
      if (data.func === 'video_tracking_fail' && data.operId) {
        // 根据operId查找对应的片段并更新状态为失败
        setSegments(prevSegments => {
          return prevSegments.map(segment => {
            if (segment.id === data.operId) {
              return {
                ...segment,
                state: 'TRACK_FAILED'
              };
            }
            return segment;
          });
        });
        // 显示失败提示
        Toast.error({ 
          content: '视频分割处理失败，请重新提交', 
          stack: true,
          id:data.operId
        });
      }
      // 处理擦除成功消息
      if (data.func === 'video_erasure_success' && data.operId) {
        setSegments(prevSegments => {
          return prevSegments.map(segment => {
            if (segment.id === data.operId) {
              return {
                ...segment,
                state: 'ERAS_SUCCESS',
              };
            }
            return segment;
          });
        });
      }
      // 处理背景替换成功消息
      if (data.func === 'video_replace_success' && data.operId) {
        setSegments(prevSegments => {
          return prevSegments.map(segment => {
            if (segment.id === data.operId) {
              return {
                ...segment,
                state: 'REPLACE_SUCCESS',
              };
            }
            return segment;
          });
        });
      }
      // 处理合成成功消息
      if (data.func === 'video_synthetic_success' && data.operId) {
        setSegments(prevSegments => {
          return prevSegments.map(segment => {
            if (segment.state =='SYNTHETICING') {
              return {
                ...segment,
                state: 'SYNTHETIC_SUCCESS',
              };
            }
            return segment;
          });
        });
      }
    };

    // 监听WebSocket消息
    sharedWebSocket.on('resp', handleWebSocketMessage);

    // 清理监听器
    return () => {
      sharedWebSocket.off('resp', handleWebSocketMessage);
    };
  }, []);

  // 处理内容擦除按钮点击
  const handleErasureClick = () => {
    setShowErasureModal(true);
  };

  // 处理背景替换按钮点击
  const handleBackgroundClick = () => {
    setShowBackgroundModal(true);
  };

  // 处理背景替换取消
  const handleBackgroundCancel = () => {
    setShowBackgroundModal(false);
    setBackgroundImage(null);
  };

  // 使用图片上传Hook
  const { handleUpload: uploadBackgroundImage, validateFile, uploading: backgroundUploading, progress: backgroundProgress } = useImageUpload({
    onSuccess: (result) => {
      setBackgroundImage({
        file: null,
        url: result.url,
        name: result.fileName || 'background.jpg'
      });
    },
    onError: (error) => {
      console.error('背景图片上传失败:', error);
    }
  });

  const handleCustomRequest = async ({file}) => {
    try {
      // 验证文件
      const isValid = await validateFile(file);
      if (!isValid) {
        return;
      }
      
      // 执行上传
      await uploadBackgroundImage(file);
      
    } catch (error) {
      console.error('背景图片上传失败:', error);
    }
  };

  // 处理背景替换确认
  const handleBackgroundConfirm = async () => {
    if (!backgroundImage || !backgroundImage.url) {
      Toast.error('请先选择背景图片');
      return;
    }
    
    try {
      // 获取当前选中片段的时间信息
      const selectedSegment = segments.find(segment => segment.selectId === selectedSegmentId);
      
      if (!selectedSegment) {
        Toast.error('请先选择要替换背景的片段');
        return;
      }

      // 构建背景替换请求参数（类似擦除接口，多一个replaceBgUrl参数）
      const requestData = {
        maskUrls: selectedSegment.maskUrls, // mask数据
        targetVideoUrl: currentVideo,
        startStamp: selectedSegment.startTime,
        endStamp: selectedSegment.endTime,
        replaceBgUrl: backgroundImage.url // 背景替换图片URL
      };

      // 调用背景替换接口
      const response = await replaceContent(requestData);
      
      // 更新片段状态
       if (response?.data?.operId && handleSegmentStateUpdate) {
         handleSegmentStateUpdate('REPLACEING', response.data.operId);
       }
      
      setShowBackgroundModal(false);
      setBackgroundImage(null);
    } catch (error) {
      Toast.error('背景替换失败');
    }
  };

  // 处理内容擦除确认
  const handleErasureConfirm = async () => {
    try {
      // 获取当前选中片段的时间信息
      const selectedSegment = segments.find(segment => segment.selectId === selectedSegmentId);

      // 构建擦除请求参数
      const requestData = {
        maskUrls: selectedSegment.maskUrls, // 这里需要根据实际情况填充mask数据
        targetVideoUrl: currentVideo,
        startStamp: selectedSegment.startTime,
        endStamp: selectedSegment.endTime
      };

      // 调用擦除接口
      const response = await erasureContent(requestData);
      
      // 更新片段状态
      if (response?.data?.operId && handleSegmentStateUpdate) {
        handleSegmentStateUpdate('ERASING', response.data.operId);
      }
      setShowErasureModal(false);
    } catch (error) {
      Toast.error({ content: '内容擦除失败', stack: true });
    }
  };

  // 处理内容擦除取消
  const handleErasureCancel = () => {
    setShowErasureModal(false);
  };

  // 处理视频合成
  const handleSyntheticVideo = async () => {
    try {
      // 将所有REPLACE_SUCCESS和ERAS_SUCCESS状态变为SYNTHETICING
      const updatedSegments = segments.map(segment => {
        if (segment.state === 'REPLACE_SUCCESS' || segment.state === 'ERAS_SUCCESS') {
          return { ...segment, state: 'SYNTHETICING' };
        }
        return segment;
      });
      setSegments(updatedSegments);
      // 构建合成参数
      const requestData = {
        targetVideoUrl: currentVideo,
        videoUrls: updatedSegments.map((segment, index) => ({
          videoIndex: index,
          startStamp: segment.startTime,
          endStamp: segment.endTime,
          videoUrl: segment.videoUrl
        }))
      };
      
      Toast.info('开始视频合成...');
      
      // 调用合成接口
      const response = await syntheticVideo(requestData);
      
      if (response?.data?.videoUrl) {
        Toast.success('视频合成成功');
        // 可以在这里处理合成结果，比如显示预览或下载链接
        console.log('合成视频URL:', response.data.videoUrl);
      }
    } catch (error) {
      Toast.error('视频合成失败');
      console.error('视频合成错误:', error);
    }
  };

  // 时间格式转换函数：将时间字符串转换为秒数
  const timeFormatToSeconds = (timeStr) => {
    if (typeof timeStr === 'number') return timeStr;
    if (!timeStr) return 0;
    const parts = timeStr.split(':');
    if (parts.length !== 3) return 0;
    
    const hours = parseInt(parts[0]) || 0;
    const minutes = parseInt(parts[1]) || 0;
    const secondsAndMs = parts[2].split('.');
    const seconds = parseInt(secondsAndMs[0]) || 0;
    const milliseconds = parseInt(secondsAndMs[1]) || 0;
    
    return hours * 3600 + minutes * 60 + seconds + milliseconds / 1000;
  };

  // 检查当前选中片段是否已提交
   const checkCurrentSegmentSubmitted = () => {
     if (!selectedSegmentId) return true; // 没有选中片段时允许操作
     
     const currentSegment = segments.find(segment => segment.selectId === selectedSegmentId);
     return currentSegment?.state !== null&&currentSegment?.state!=='SUBMITTED'; // state为null表示未提交
   };

   // 新增片段功能
   const handleAddSegment = () => {
     // 检查当前片段是否已提交
     if (!checkCurrentSegmentSubmitted()) {
       Toast.warning({ content: '请先提交当前片段后再进行此操作', stack: true });
       return;
     }
    // 获取当前视频时间
    const video = document.querySelector('video');
    if (!video) {
      console.warn('未找到视频元素');
      return;
    }
    
    video.pause();
    const currentVideoTime = video.currentTime;
    const videoDuration = video.duration || 0;
    
    // 检查当前时间是否在已有片段内
    const isInExistingSegment = segments.some(segment => 
      currentVideoTime >= timeFormatToSeconds(segment.startTime) && 
      currentVideoTime <= timeFormatToSeconds(segment.endTime)
    );
    
    if (isInExistingSegment) {
      Toast.error({ content: '当前范围无法添加片段', stack: true });
      return;
    }
    
    // 计算可用的时间范围，避免与已有片段重叠
    const findAvailableTimeRange = (currentTime, targetDuration = 6) => {
      const minDuration = 0.5; // 最小0.5秒
      
      // 如果没有已有片段，直接使用理想范围
      if (segments.length === 0) {
        let idealStart = Math.max(0, currentTime - 3);
        let idealEnd = Math.min(videoDuration, currentTime + 3);
        
        // 处理边界情况
        if (idealStart === 0) {
          idealEnd = Math.min(videoDuration, idealEnd + (3 - currentTime));
        }
        if (idealEnd === videoDuration) {
          idealStart = Math.max(0, idealStart - (currentTime + 3 - videoDuration));
        }
        
        if (idealEnd - idealStart >= minDuration) {
          return { start: idealStart, end: idealEnd };
        }
        return null;
      }
      
      // 按开始时间排序已有片段
      const sortedSegments = [...segments]
        .map(segment => ({
          start: timeFormatToSeconds(segment.startTime),
          end: timeFormatToSeconds(segment.endTime)
        }))
        .sort((a, b) => a.start - b.start);
      
      // 检查时间范围是否与已有片段冲突
      const hasConflict = (start, end) => {
        return sortedSegments.some(segment => 
          !(end <= segment.start || start >= segment.end)
        );
      };
      
      // 理想范围：当前时间前后各3秒
      let idealStart = Math.max(0, currentTime - 3);
      let idealEnd = Math.min(videoDuration, currentTime + 3);
      
      // 如果理想范围无冲突，直接使用
      if (!hasConflict(idealStart, idealEnd)) {
        return { start: idealStart, end: idealEnd };
      }
      
      // 寻找当前时间附近最大可用空间
      let availableStart = 0;
      let availableEnd = videoDuration;
      
      // 找到当前时间前面最近的片段结束时间
      for (const segment of sortedSegments) {
        if (segment.end <= currentTime) {
          availableStart = Math.max(availableStart, segment.end);
        }
      }
      
      // 找到当前时间后面最近的片段开始时间
      for (const segment of sortedSegments) {
        if (segment.start >= currentTime) {
          availableEnd = Math.min(availableEnd, segment.start);
          break;
        }
      }
      
      // 检查可用空间是否足够最小时长
      if (availableEnd - availableStart < minDuration) {
        return null;
      }
      
      // 在可用空间内，尽量以当前时间为中心
      const availableSize = availableEnd - availableStart;
      const targetSize = Math.min(6, availableSize);
      
      let finalStart = currentTime - targetSize / 2;
      let finalEnd = currentTime + targetSize / 2;
      
      // 调整到可用范围内
      if (finalStart < availableStart) {
        finalStart = availableStart;
        finalEnd = availableStart + targetSize;
      }
      if (finalEnd > availableEnd) {
        finalEnd = availableEnd;
        finalStart = availableEnd - targetSize;
      }
      
      return { start: finalStart, end: finalEnd };
    };
    
    const timeRange = findAvailableTimeRange(currentVideoTime, 6);
    if (!timeRange) {
      console.warn('当前范围无法添加片段');
      return;
    }
    

    
    // 生成缩略图 - 始终从视频当前帧截图
    let thumbnailUrl = '';
    try {
      // 确保视频已加载且可以绘制
      if (video.readyState >= 2) {
        // 创建canvas来截取视频当前帧
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        canvas.width = video.videoWidth || 640;
        canvas.height = video.videoHeight || 360;
        
        // 将视频当前帧绘制到canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // 转换为JPEG格式的数据URL
        thumbnailUrl = canvas.toDataURL('image/jpeg', 0.8);
      } else {
        console.warn('视频尚未完全加载，无法生成缩略图');
      }
    } catch (error) {
      console.warn('生成缩略图失败，可能是跨域问题:', error.message);
      thumbnailUrl = '';
    }
    // 生成新的片段数据
    const newSegment = {
      id: `segment_${Date.now()}`,
      selectId: `action_${Date.now()}`,
      startTime: formatTimeToString(timeRange.start),
      endTime: formatTimeToString(timeRange.end),
      duration: timeRange.end - timeRange.start,
      coverImgUrl: thumbnailUrl,
      currentTime: currentVideoTime,
      state: null // 未提交状态
    };
    
    // 生成时间轴action
    const newAction = {
      id: newSegment.selectId, // 使用与segment相同的id
      start: timeRange.start,
      end: timeRange.end,
      type: 'segment',
      movable: false
    };
    
    // 添加到片段列表（插入到开头）
    setSegments(prevSegments => [newSegment, ...prevSegments]);
    
    // 添加到时间轴数据（插入到开头）
    setTimelineData(prevData => {
      const updatedData = [...prevData];
      if (updatedData.length > 0) {
        updatedData[0] = {
          ...updatedData[0],
          actions: [newAction, ...updatedData[0].actions]
        };
      }
      return updatedData;
    });
    
    // 选中新创建的片段
     setSelectedSegmentId(newSegment.selectId);
   };

   // 删除片段功能
   const handleDeleteSegment = (segmentId) => {
     // 从片段列表中移除
     setSegments(prevSegments => prevSegments.filter(segment => segment.selectId !== segmentId));
     
     // 从时间轴数据中移除对应的action
     setTimelineData(prevData => {
       const updatedData = [...prevData];
       if (updatedData.length > 0) {
         updatedData[0] = {
           ...updatedData[0],
           actions: updatedData[0].actions.filter(action => action.id !== segmentId)
         };
       }
       return updatedData;
     });
     
     // 如果删除的是当前选中的片段，清除选中状态并清空画布
     if (selectedSegmentId === segmentId) {
       setSelectedSegmentId(null);
       // 清空画布内容
       if (resultsContainerRef.current?.clearCanvas) {
         resultsContainerRef.current.clearCanvas();
       }
     }
   };

   // 片段点击处理
   const handleSegmentClick = (segmentId) => {
     // 如果点击的是当前选中的片段，直接返回
     if (segmentId === selectedSegmentId) {
       return;
     }
     
     // 检查当前片段是否已提交
     if (!checkCurrentSegmentSubmitted()) {
       Toast.warning({ content: '请先提交当前片段后再进行此操作', stack: true });
       return;
     }
     
     setSelectedSegmentId(segmentId);
   };
  
  // 处理显示状态变化的回调函数
  const handleShowStateChange = (newState) => {
    if (newState.showBottom !== undefined) {
      setShowBottom(newState.showBottom);
    }
    if (newState.showMainEdit !== undefined) {
      setShowMainEdit(newState.showMainEdit);
    }
  };


  
  // 跟踪画布数据状态
  const [selectedPoints, setSelectedPoints] = useState([]);
  const [selectGreenPoints, setSelectGreenPoints] = useState([]);
  const [selectionRects, setSelectionRects] = useState([]);
  const [brushStrokes, setBrushStrokes] = useState([]);
  const [erasureText, setErasureText] = useState(''); // segmentation工具的文本输入
  const [showErasureModal, setShowErasureModal] = useState(false); // 内容擦除确认弹框
  const [showBackgroundModal, setShowBackgroundModal] = useState(false); // 背景替换弹框
  const [backgroundImage, setBackgroundImage] = useState(null); // 背景图片 {file, url, name}
  const [selectedPreviewMode, setSelectedPreviewMode] = useState('original'); // 预览模式：'original' 或 'result'

  // 当选中片段变化时，检查是否需要切换回原视频模式
  useEffect(() => {
    const selectedSegment = segments.find(segment => segment.selectId === selectedSegmentId);
    if (selectedPreviewMode === 'result' && !selectedSegment?.videoUrl) {
      setSelectedPreviewMode('original');
    }
  }, [selectedSegmentId, segments, selectedPreviewMode]);
  
  const handleToolChange = (toolKey) => {
    // 如果点击的是当前已选中的工具，则取消选中
    if (selectedTool === toolKey) {
      setSelectedTool(null); // 取消选中，此时可以拖动图片
      return;
    }
    
    setSelectedTool(toolKey);
    // 切换工具时清空相关数据状态
    setSelectedPoints([]);
    setSelectGreenPoints([]);
    setSelectionRects([]);
    setBrushStrokes([]);
    setErasureText(''); // 清空文本输入
    // 清空画布内容
    if (resultsContainerRef.current?.clearCanvas) {
      resultsContainerRef.current.clearCanvas();
    }
  };

  useEffect(() => {
    // 切换工具时清空相关数据状态
    setSelectedPoints([]);
    setSelectGreenPoints([]);
    setSelectionRects([]);
    setBrushStrokes([]);
    setErasureText(''); // 清空文本输入
    // 清空画布内容
    if (resultsContainerRef.current?.clearCanvas) {
      resultsContainerRef.current.clearCanvas();
    }
  }, [selectedRatio]);

  useEffect(() => {
    if(step==0){
      dispatch(clearLayerVideo())
      // 切换工具时清空相关数据状态
      setSelectedPoints([]);
      setSelectGreenPoints([]);
      setSelectionRects([]);
      setBrushStrokes([]);
      setErasureText(''); // 清空文本输入
      setSelectedTool(null);
      setToolSize(20)
      // 清空画布内容
      if (resultsContainerRef.current?.clearCanvas) {
        resultsContainerRef.current.clearCanvas();
      }
    }
  }, [step]);
  
  const handleToolSizeChange = (size) => {
    setToolSize(size);
  };
  
  // 处理点选变化
  const handlePointSelectionChange = (points) => {
    console.log('选中的点(原图坐标):', points);
    setSelectedPoints(points);
  };

  // 处理绿色点变化
  const handleGreenPointSelectionChange = (points) => {
    console.log('绿色点(原图坐标):', points);
    setSelectGreenPoints(points);
  };
  
  // 处理框选变化
  const handleRectSelectionChange = (rects) => {
    console.log('框选区域(原图坐标):', rects);
    setSelectionRects(rects);
  };
  
  // 处理画笔笔触变化
  const handleBrushStrokesChange = (strokes) => {
    setBrushStrokes(strokes);
  };
  
  // 判断是否有数据可以提交
  const hasDataToSubmit = useMemo(() => {
    return selectedSegmentId && (selectedPoints.length > 0 || selectionRects.length > 0 || brushStrokes.length > 0 || selectedTool === 'segmentation' || selectedTool === 'preset');
  }, [selectedSegmentId, selectedPoints, selectionRects, brushStrokes, selectedTool, erasureText]);

  // 处理片段状态更新
  const handleSegmentStateUpdate = (newState, newId = null) => {    
    setSegments(prevSegments => {
      return prevSegments.map(segment => {
        if (segment.selectId === selectedSegmentId) {
          const updatedSegment = {
            ...segment,
            state: newState
          };
            updatedSegment.id = newId;
            // 更新timelineData中对应的action id
            setTimelineData(prevData => {
              const updatedData = [...prevData];
              if (updatedData.length > 0) {
                updatedData[0] = {
                  ...updatedData[0],
                  actions: updatedData[0].actions.map(action => {
                    if (action.id === selectedSegmentId) {
                      return {
                        ...action,
                        id: newId||action.id,
                        flexible: true
                      };
                    }
                    return action;
                  })
                };
              }
              return updatedData;
            });
          return updatedSegment;
        }
        return segment;
      });
    });
  };
  


  const [typeValue, setTypeValue] = useState(1);
  const handleTypeChange = (e) => {
    const newValue = e.target.value ? e.target.value : 1;
    setTypeValue(newValue);
  };

  const [proportion, setProportion] = useState('16:9');
  const [qualityValue, setQualityValue] = useState('1K');
  const [quantityValue, setQuantityValue] = useState(1);
  
  return (
    <div className={styles.imageEditPage} id='imageEditPage'>
      <div className={styles.mainSection}>
        <div className={styles.mainContent}>
          {showMainEdit&&<MainEdit
            typeValue={typeValue}
            onTypeChange={handleTypeChange}
            proportion={proportion}
            setProportion={setProportion}
            qualityValue={qualityValue}
            setQualityValue={setQualityValue}
            quantityValue={quantityValue}
            setQuantityValue={setQuantityValue}
            selectedTool={selectedTool}
            onToolChange={handleToolChange}
            toolSize={toolSize}
            onToolSizeChange={handleToolSizeChange}
            currentVideo={currentVideo}
            selectedRatio={selectedRatio}
            setSelectedRatio={setSelectedRatio}
            hasDataToSubmit={hasDataToSubmit}
            selectedPoints={selectedPoints}
            selectGreenPoints={selectGreenPoints}
            selectionRects={selectionRects}
            brushStrokes={brushStrokes}
            canvasDrawingRef={resultsContainerRef}
            erasureText={erasureText}
            setErasureText={setErasureText}
            onShowStateChange={handleShowStateChange}
            step={step}
            onStepChange={setStep}
            segments={segments}
            selectedSegmentId={selectedSegmentId}
            onAddSegment={handleAddSegment}
            onDeleteSegment={handleDeleteSegment}
            onSegmentClick={handleSegmentClick}
            onSegmentStateUpdate={handleSegmentStateUpdate}
            selectedPreviewMode={selectedPreviewMode}
            hasPreviewVideo={!!segments.find(segment => segment.selectId === selectedSegmentId)?.videoUrl}
            onSyntheticVideo={handleSyntheticVideo}
          />}
          {showResults && (
            <div className={styles.resultsSection}>
              {currentVideo&&(
                <>
                  <div style={{height: '40px',color: '#fff',display: 'flex',alignItems: 'center',padding: '4px 12px',justifyContent: 'space-between'}}>
                  <div style={{
                    display:'flex',
                    lineHeight: '24px',
                    height: '32px',
                    alignItems: 'center',
                    textAlign: 'center',
                    borderRadius: '8px',
                    background: 'rgba(13, 12, 16, 1)'}}>
                      <div 
                        style={{
                          width: '116px',
                          cursor: 'pointer',
                          background: selectedPreviewMode === 'original' ? 'rgba(255, 255, 255, 0.2)' : 'transparent',
                          borderRadius: '4px'
                        }}
                        onClick={() => {
                          setSelectedPreviewMode('original');
                          // 如果当前是播放状态，切换到原视频时也要播放
                          if (isVideoPlaying) {
                            setTimeout(() => {
                              const video = document.querySelector('video#current-video');
                              if (video && video.paused) {
                                video.play().catch(console.error);
                              }
                            }, 100);
                          }
                        }}
                      >
                        原视频
                      </div>
                      <div 
                        style={{
                          width: '116px',
                          cursor: segments.find(segment => segment.selectId === selectedSegmentId)?.videoUrl ? 'pointer' : 'not-allowed',
                          background: selectedPreviewMode === 'result' ? 'rgba(255, 255, 255, 0.2)' : 'transparent',
                          borderRadius: '4px',
                          opacity: segments.find(segment => segment.selectId === selectedSegmentId)?.videoUrl ? 1 : 0.5
                        }}
                        onClick={() => {
                          const selectedSegment = segments.find(segment => segment.selectId === selectedSegmentId);
                          if (!selectedSegment?.videoUrl) {
                            return; // 如果没有videoUrl，不允许切换
                          }
                          setSelectedPreviewMode('result');
                          // 如果当前是播放状态，切换到预览视频时也要播放
                          if (isVideoPlaying) {
                            setTimeout(() => {
                              const previewVideo = document.querySelector('#preview-video');
                              if (previewVideo && previewVideo.paused) {
                                previewVideo.play().catch(console.error);
                              }
                            }, 100);
                          }
                        }}
                      >
                        分割结果预览
                      </div>
                    </div>
                    <div>
                      <Image src={download} preview={false} draggable={false} />
                      下载
                    </div>
                  </div>
                  {selectedPreviewMode=='result' && segments.find(segment => segment.selectId === selectedSegmentId)?.videoUrl && !videoLoadError && <div style={{padding:'8px 12px',display:'flex',gap:'16px'}}>
                    <Button
                      style={{width:'172px'}}
                      className='button buttonPrimary'
                      onClick={handleBackgroundClick}
                      disabled={!segments.find(segment => segment.selectId === selectedSegmentId && segment.state === 'TRACK_SUCCESS')}
                    >
                      背景替换
                    </Button>
                    <Button
                      style={{width:'172px'}}
                      className='button buttonPrimary'
                      onClick={handleErasureClick}
                      disabled={!segments.find(segment => segment.selectId === selectedSegmentId && segment.state === 'TRACK_SUCCESS')}
                    >
                      视频擦除
                    </Button>
                  </div>}
                </>
              )}
              <Results 
                ref={resultsContainerRef}
                selectedTool={selectedTool}
                toolSize={toolSize}
                onPointSelectionChange={handlePointSelectionChange}
                onGreenPointSelectionChange={handleGreenPointSelectionChange}
                onBrushStrokesChange={handleBrushStrokesChange}
                onRectSelectionChange={handleRectSelectionChange}
                hideUploadArea={false}
                onStepChange={setStep}
                step={step}
                selectedSegment={segments.find(segment => segment.selectId === selectedSegmentId)}
                selectedPreviewMode={selectedPreviewMode}
                currentVideo={currentVideo}
                previewVideoUrl={segments.find(segment => segment.selectId === selectedSegmentId)?.videoUrl}
                currentVideoTime={currentVideoTime}
                isVideoPlaying={isVideoPlaying}
                onVideoTimeUpdate={setCurrentVideoTime}
                videoLoadError={videoLoadError}
                onVideoLoadError={setVideoLoadError}
              />
              {/* 视频播放控制组件 */}
              {currentVideo && !(selectedPreviewMode === 'result' && (!segments.find(segment => segment.selectId === selectedSegmentId)?.videoUrl || videoLoadError)) && <div className={styles.videoControls}>
                <div className={styles.progressContainer}>
                  <div className={styles.timeDisplay}>
                    <span className={styles.currentTime}>{formatTime(currentVideoTime)}</span>
                  </div>
                  <div className={styles.progressBar} onClick={handleProgressClick}>
                    <div 
                      className={styles.progressFill} 
                      style={{ width: `${(currentVideoTime / videoDuration) * 100}%` }}
                    ></div>
                    <div 
                      className={styles.progressThumb}
                      style={{ left: `${(currentVideoTime / videoDuration) * 100}%` }}
                    ></div>
                  </div>
                  <div className={styles.timeDisplay}>
                    <span className={styles.totalTime}>{formatTime(videoDuration)}</span>
                  </div>
                </div>
                <div className={styles.controlButtons}>
                  <button className={styles.controlBtn} onClick={handleRewind}>
                    <svg viewBox="0 0 10 10">
                      <defs>
                        <linearGradient id="buttonGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                          <stop offset="0%" stopColor="#FFFFFF" />
                          <stop offset="100%" stopColor="rgba(225, 244, 255, 0.45)" />
                        </linearGradient>
                      </defs>
                      <path d="M10 0 L0 5 L10 10 Z" fill="url(#buttonGradient)" />
                    </svg>
                  </button>
                  <button className={styles.playBtn} onClick={handlePlayPause}>
                    {isVideoPlaying ? (
                      <svg viewBox="0 0 10 10">
                        <defs>
                          <linearGradient id="pauseGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                            <stop offset="0%" stopColor="#FFFFFF" />
                            <stop offset="100%" stopColor="rgba(225, 244, 255, 0.45)" />
                          </linearGradient>
                        </defs>
                        <path d="M0 0 L10 0 L10 10 L0 10 Z" fill="url(#buttonGradient)" />
                      </svg>
                    ) : (
                      <svg viewBox="0 0 10 10">
                        <defs>
                          <linearGradient id="playGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                            <stop offset="0%" stopColor="#FFFFFF" />
                            <stop offset="100%" stopColor="rgba(225, 244, 255, 0.45)" />
                          </linearGradient>
                        </defs>
                        <path d="M0 0 L10 5 L0 10 Z" fill="url(#playGradient)" />
                      </svg>
                    )}
                  </button>
                  <button className={styles.controlBtn} onClick={handleFastForward}>
                    <svg viewBox="0 0 10 10">
                      <defs>
                        <linearGradient id="forwardGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                          <stop offset="0%" stopColor="#FFFFFF" />
                          <stop offset="100%" stopColor="rgba(225, 244, 255, 0.45)" />
                        </linearGradient>
                      </defs>
                      <path d="M0 0 L10 5 L0 10 Z" fill="url(#forwardGradient)" />
                    </svg>
                  </button>
                </div>
              </div>}
            </div>
          )}
        </div>
        <div className={`${styles.timelineWrap} ${step==0 ? 'is-hidden' : ''}`}>
          <Timeline
            ref={timelineRef}
            editorData={timelineData}
            gridSnap={timelineConfig.scale == 5 ? true : false}
            dragLine={timelineConfig.scale == 5 ? true : false}
            effects={{}}
            onChange={(data) => {
              setTimelineData(data);
            }}
            onCursorDrag={(time) => {
              // 时间轴拖拽时，视频跳转到对应位置 - 直接使用秒
              const video = document.querySelector('video');
              if (video) {
                if (time <= video.duration) {
                  video.currentTime = time;
                } else {
                  video.currentTime = video.duration;
                }
              }
            }}
            onClickTimeArea={(time) => {
              // 时间轴点击时，视频跳转到对应位置 - 直接使用秒
              const video = document.querySelector('video');
              if (video) {
                if (time <= video.duration) {
                  video.currentTime = time;
                } else {
                  video.currentTime = video.duration;
                }
              }
            }}
            onActionResizing={({ start, end, action }) => {
              const video = document.querySelector('video');
              // 直接使用秒进行时间计算
              const segmentDuration = end - start;
              
              // 检查时长限制（0.5-10秒）
              if (segmentDuration < 0.5 || segmentDuration > 10) {
                return false;
              }

              // 检查是否超过视频总时长
              if (video && video.duration) {
                if (end > video.duration) {
                  return false;
                }
              }

              // 检查开始时间是否小于0
              if (start < 0) {
                return false;
              }

              // 检查是否与其他片段重叠
              const otherSegments = segments.filter(segment => segment.selectId !== action.id);
              const hasConflict = otherSegments.some(segment => {
                const segStart = timeFormatToSeconds(segment.startTime);
                const segEnd = timeFormatToSeconds(segment.endTime);
                return !(end <= segStart || start >= segEnd);
              });
              
              if (hasConflict) {
                return false;
              }
              
              return true;
            }}
            onActionResizeEnd={({ start, end, dir, action }) => {
              const video = document.querySelector('video');
              if (video && action) {
                const timeInSeconds = dir === 'right' ? end : start;
                
                // 跳转到调整后的时间点
                if (timeInSeconds <= video.duration) {
                  video.currentTime = timeInSeconds;
                } else {
                  video.currentTime = video.duration;
                }
                
                // 等待视频跳转完成后生成截图并更新数据
                const generateThumbnailAndUpdate = () => {
                  // 生成当前时间的封面图
                  let thumbnailUrl = '';
                  
                  // 如果时间为0则直接使用默认封面图
                  if (timeInSeconds === 0) {
                    thumbnailUrl = '';
                  } else {
                    try {
                      const canvas = document.createElement('canvas');
                      const ctx = canvas.getContext('2d');
                      canvas.width = video.videoWidth || 640;
                      canvas.height = video.videoHeight || 360;
                      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                      thumbnailUrl = canvas.toDataURL('image/jpeg', 0.8);
                    } catch (error) {
                      console.warn('无法生成视频封面图，可能是跨域问题:', error);
                      thumbnailUrl = '';
                    }
                  }
                  
                  // 更新timelineData中对应action的时间和缩略图
                  setTimelineData(prevData => {
                    return prevData.map(segment => ({
                      ...segment,
                      actions: segment.actions.map(act =>
                        act.id === action.id
                          ? { ...act, start, end, thumbnailUrl }
                          : act
                      )
                    }));
                  });
                  
                  // 同步更新segments的时间信息和封面图
                  setSegments(prevSegments =>
                    prevSegments.map(segment =>
                      segment.selectId === action.id
                        ? {
                          ...segment,
                          startTime: formatTimeToString(start),
                          endTime: formatTimeToString(end),
                          coverImgUrl: thumbnailUrl
                        }
                        : segment
                    )
                  );
                };
                
                // 如果视频已经在目标时间，直接生成截图
                if (Math.abs(video.currentTime - timeInSeconds) < 0.1) {
                  setTimeout(generateThumbnailAndUpdate, 500);
                } else {
                  // 等待视频跳转完成
                  const handleSeeked = () => {
                    video.removeEventListener('seeked', handleSeeked);
                    setTimeout(generateThumbnailAndUpdate, 100);
                  };
                  video.addEventListener('seeked', handleSeeked);
                }
              }
            }}
            getActionRender={(action, row) => {
              if (action.flexible == undefined) {
                return <div style={{ height: '100%', background: 'rgba(102, 51, 238, 0.9)' }}></div>
              }
            }}
            autoScroll={true}
            scale={timelineConfig.scale}
            startLeft={timelineConfig.startLeft}
            minScaleCount={Math.max(
              Math.ceil(document.querySelector(`.${styles.timelineWrap}`)?.clientWidth / timelineConfig.scaleWidth || 1),
              Math.floor((videoDuration || 60) / timelineConfig.scale) + 1 // 使用实际视频时长
            )}
            scaleWidth={timelineConfig.scaleWidth}
            scaleSplitCount={timelineConfig.scaleSplitCount}
            hideCursor={false}
            getScaleRender={(scale) => {
              const video = document.querySelector('video');
              const duration = video?.duration || 60;
              
              // 超过视频时长的刻度不显示
              if (scale > Math.ceil(duration)) return '';
              
              if (scale === 0) return '0:00';
              
              const minutes = Math.floor(scale / 60);
              const seconds = scale % 60;
              
              if (minutes > 0) {
                return `${minutes}:${seconds.toString().padStart(2, '0')}`;
              } else {
                return `0:${seconds.toString().padStart(2, '0')}`;
              }
            }}
          ></Timeline>
        </div>
      </div>
      
      {/* 内容擦除确认弹框 */}
       <Modal
         title="提示"
         visible={showErasureModal}
         width={600}
         height={240}
         centered={true}
         onCancel={handleErasureCancel}
         footer={
           <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
             <Button 
               className="button buttonDefault"
               onClick={handleErasureCancel}
               style={{ width: '120px' }}
             >
               取消
             </Button>
             <Button 
               className="button buttonPrimary"
               onClick={handleErasureConfirm}
               style={{ width: '327px' }}
             >
               执行
             </Button>
           </div>
         }
       >
         <div style={{display:'flex',height:'100%',alignItems:'center',justifyContent:'center'}}>是否执行擦除任务</div>
       </Modal>

       {/* 背景替换弹框 */}
       <Modal
         title="提示"
         visible={showBackgroundModal}
         width={600}
         height={400}
         centered={true}
         onCancel={handleBackgroundCancel}
         footer={
           <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
             <Button 
               className="button buttonDefault"
               onClick={handleBackgroundCancel}
               style={{ width: '120px' }}
             >
               取消
             </Button>
             <Button 
               className="button buttonPrimary"
               onClick={handleBackgroundConfirm}
               style={{ width: '327px' }}
             >
               替换背景
             </Button>
           </div>
         }
       >
         <div style={{display:'flex',flexDirection:'column',height:'100%',alignItems:'center',justifyContent:'center',gap:'20px'}}>
           <Upload
            action="/"
            accept=".jpg,.jpeg,.png"
            customRequest={handleCustomRequest}
            draggable={true}
            showUploadList={false}
            style={{width:'100%',height:'100%'}}
            disabled={backgroundUploading}
           >
             {backgroundImage && backgroundImage.url ? (
               <div style={{width:'100%',height:'100%',position:'relative',display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:'8px'}}>
                 <Image
                   src={backgroundImage.url}
                   alt="背景图片预览"
                   preview={false}
                   draggable={false}
                   style={{
                    width: '100%',
                    height: '230px',
                    objectFit: 'cover',
                    borderRadius: '4px'
                   }}
                 />
               </div>
             ) : (
               <div 
                 className={styles.uploadSection}
                 style={{width:'100%',height:'100%',cursor: backgroundUploading ? 'not-allowed' : 'pointer'}}
               >
                 <div className={styles.uploadPlaceholder}>
                   {backgroundUploading ? (
                     <div style={{display:'flex',flexDirection:'column',alignItems:'center',gap:'4px'}}>
                       <div style={{fontSize:'12px',color:'#666'}}>上传中... {backgroundProgress}%</div>
                     </div>
                   ) : (
                     <>
                       <Image 
                         src={add_gray} 
                         preview={false} 
                         className={styles.uploadIcon} 
                         draggable={false} 
                       /> 
                       <div className={styles.uploadText}> 
                         添加背景
                       </div>
                     </>
                   )}
                 </div>
               </div>
             )}
           </Upload>
         </div>
       </Modal>
    </div>
  );
}
